package br.com.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

import org.apache.log4j.Logger;

import br.com.logistica.base.BaseDAO;
import br.com.logistica.database.FactoryJPA;
import br.com.smart.logistica.services.ClienteSCN;

import com.thoughtworks.xstream.XStream;

public class QueryUtil extends BaseDAO {
	private static Logger logger = Logger.getLogger(QueryUtil.class);
	private static final String QUERY_FILE = "query.properties";
	private static XStream xstream = new XStream();

	public static XStream getXstream() {
		return xstream;

	}

	private static <T> List<Predicate> retornaPredicate(
			HashMap<String, Object> hashMap, CriteriaBuilder criteriaBuilder,
			Root<Class<T>> from) {
		ArrayList<Predicate> result = new ArrayList<Predicate>();

		for (Entry<String, Object> e : hashMap.entrySet()) {
			Predicate p1 = criteriaBuilder.equal(from.get(e.getKey()),
					e.getValue());

			result.add(p1);
		}

		return (result);
	}

	public static <T> ArrayList<T> fazerConsultaDinamica(
			HashMap<String, Object> hashMap, Class<T> classe) {
		// hashMap.put("id do objeto", 12)pontto e virgula
		// hashMap.get(arg0)

		EntityManager em = null;
		try {
			em = FactoryJPA.getInstance(baseEnum);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
		CriteriaQuery<T> query = criteriaBuilder.createQuery(classe);
		Root<Class<T>> from = (Root<Class<T>>) query.from(classe);
		List<Predicate> predicates = retornaPredicate(hashMap, criteriaBuilder,
				from);
		TypedQuery<Class<T>> type = (TypedQuery<Class<T>>) em.createQuery(query
				.select((Selection<? extends T>) predicates));
		List<Class<T>> resultList = type.getResultList();

		return ((ArrayList<T>) resultList);
	}

	public static String getQuery(String key) {
		Properties properties = new Properties();

		try {
			FileInputStream fis = new FileInputStream(QUERY_FILE);

			properties.load(fis);
		} catch (IOException e) {
			logger.error(e);
		}

		return (properties.getProperty(key));
	}
}
